package com.screen.screendisplay.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.screen.screendisplay.entity.coal.CoalOpermonRtEffect;
import com.screen.screendisplay.mapper.coal.CoalOpermonRtEffectMapper;
import com.screen.screendisplay.service.coal.CoalOpermonRtEffectService;
import com.screen.screendisplay.vo.coal.CoalProductionEfficiencyVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 运行检测生产效能表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalOpermonRtEffectServiceImpl extends ServiceImpl<CoalOpermonRtEffectMapper, CoalOpermonRtEffect> implements CoalOpermonRtEffectService {

    @Override
    public List<CoalProductionEfficiencyVO> getProductionEfficiency(Integer year) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        
        // 计算6个月前的日期
        LocalDate sixMonthsAgo = currentDate.minusMonths(5);
        
        // 查询最近6个月的数据
        LambdaQueryWrapper<CoalOpermonRtEffect> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(CoalOpermonRtEffect::getYear, sixMonthsAgo.getYear())
               .orderByDesc(CoalOpermonRtEffect::getYear)
               .orderByDesc(CoalOpermonRtEffect::getMonth);
        
        List<CoalOpermonRtEffect> effectList = this.list(wrapper);
        
        // 按年月分组取最新数据
        Map<String, CoalOpermonRtEffect> monthlyDataMap = new HashMap<>();
        
        for (CoalOpermonRtEffect effect : effectList) {
            String yearMonth = effect.getYear() + "-" + effect.getMonth();
            // 只保留每个月的第一条记录（因为已按年月降序排序）
            if (!monthlyDataMap.containsKey(yearMonth)) {
                monthlyDataMap.put(yearMonth, effect);
            }
        }
        
        // 转换为VO列表
        List<CoalProductionEfficiencyVO> resultList = new ArrayList<>();
        
        // 生成最近6个月的数据
        for (int i = 0; i < 6; i++) {
            LocalDate monthDate = currentDate.minusMonths(i);
            String yearMonth = monthDate.getYear() + "-" + monthDate.getMonthValue();
            
            CoalProductionEfficiencyVO vo = new CoalProductionEfficiencyVO();
            vo.setYear(monthDate.getYear());
            vo.setMonth(monthDate.getMonthValue());
            
            CoalOpermonRtEffect effect = monthlyDataMap.get(yearMonth);
            if (effect != null) {
                vo.setStrippingEfficiency(effect.getStrippingEfficiency());
                vo.setOverallEfficiency(effect.getOverallEfficiency());
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }
}
